package com.pipayshop.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 * Redis 配置类
 */
@Configuration
public class RedisConfig {
    @Value("${redis.config.host}")
    private String host;
    @Value("${redis.config.port}")
    private Integer port;
    @Value("${redis.config.password}")
    private String password;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        // 使用 RedisStandaloneConfiguration 配置连接
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);   // 设置 Redis 主机名
        config.setPort(port);               // 设置 Redis 端口
        config.setPassword(password);          // 设置 Redis 密码（如需要）
        // 将配置传递给 JedisConnectionFactory
        return new JedisConnectionFactory(config);
    }

    // 配置 RedisTemplate序列化与反序列化
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        return template;
    }

    @Bean
    public RedissonClient redissonClient() {
        // 配置类
        Config config = new Config();
        // 添加redis地址，这里添加了单点的地址，也可以使用config.useClusterServers()添加集群地址
//        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("123");
        config.useSingleServer()
                .setAddress("redis://"+host+":"+port)
                .setPassword("123")
                .setTimeout(20000)
                .setRetryInterval(1000)
                .setRetryAttempts(3);
        // 创建客户端
        return Redisson.create(config);
    }

}
